<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="注册  /  登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 登录表单 -->
    <van-form @submit="onLogin" 
              :show-error="false"
              :show-error-message="false"
              validate-first
              ref="login-form"
              @failed="onFailed" >
      <van-field
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        center
        placeholder="请输入手机号"
        name="mobile"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        icon-prefix="toutiao"
        clearable
        left-icon="yanzhengma"
        center
        placeholder="请输入验证码"
        name="code"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down :time="1000 * 60" format="ss s" v-if="isCountDownShow" @finish="isCountDownShow = false"/>
          <van-button size="small" round class="send-btn" @click.prevent="onSendSms" v-else :loading="isSendSmsLoading">获取验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
          <van-button type="info" block class="login-btn">登录</van-button>
      </div>
    </van-form>

  </div>
</template>

<script>
import {login, sendSms} from '@/api/user'
// import {Toast} from 'vant'

export default {
data() {
  return {
    user:{
      mobile:'',//手机号
      code:'' //验证码
    },
    formRules:{
      mobile:[
        {required: true, message: '请填写手机号'},
        {pattern:/^1[3|5|7|8|9]\d{9}$/,message:'手机号格式错误'}
      ],
      code:[
        {required: true, message: '请填写验证码'},
        {pattern:/^\d{6}$/,message:'验证码格式错误'}
      ]
    },
    isCountDownShow:false,
    isSendSmsLoading:false,
    // 用户登录信息临时声明变量


  }
},
methods: {
  async onLogin(){
    this.$toast.loading({
      message: '登录中...',
      forbidClick: true,
      duration:0
    });
    try {
      const res = await login(this.user)
      this.$toast.success('登录成功')
      // 将后端返回的Token放到vuex里
      this.$store.commit('setUser', res.data.data)

      this.$store.commit('removeCachePage', 'LayoutIndex')

      this.$router.push(this.$route.query.redirect || '/')
    } catch (err) {
      this.$toast.fail('登录失败，手机号或验证码错误')
    }

  },
  onFailed(error){
    if(error.errors[0]){
      this.$toast({
        message:error.errors[0].message,
        position:'top'
      })
    }
  },
  async onSendSms(){
    try {
      await this.$refs['login-form'].validate('mobile')
      const res = await sendSms(this.user.mobile)
      console.log(res);
      this.isSendSmsLoading = true
      this.isCountDownShow = true
    } catch (err) {
      let message= ''
      if (err && err.response && err.response.status === 429) {
        message = '发送太频繁了，请稍后重试~'
      }else if (err.name === 'mobile') {
        message = err.message
      }else{
        message = '发送失败，请稍后重试'
      }
      this.$toast({
        message,
        position:'top'
      })
    }
    this.isSendSmsLoading = false
  }
},
}
</script>

<style lang="less" scoped>

.login-container{
    .send-btn{
      width: 78px;
      height: 23px;
      background-color: #ededed;
      .van-button__text{
        font-size: 11px;
        color: #666;
      }
}
.login-btn-wrap{
  padding: 26px 16px;
  .login-btn{
    background-color: #6db4fb;
    border: none;
    .van-button__text{
      font-size: 15px;
    }
  }
}
.van-cell {
    font-size: 16px;
    align-items: center;
  }
}

</style>